package com.shuqi.activity.Fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.shuqi.activity.ActivityManager;
import com.shuqi.activity.OfferWallItemActivity;
import com.shuqi.activity.OfferWallTopActivity;
import com.shuqi.activity.adapter.OfferWallGridAdapter;
import com.shuqi.activity.adapter.OfferWallListAdapter;
import com.shuqi.activity.viewport.MyListFooter;
import com.shuqi.activity.viewport.MyListFooter.MyFooterListener;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.NetErrorProvider;
import com.shuqi.common.NetErrorProvider.NetErrorListener;
import com.shuqi.common.utils.Util;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.OfferWallModel;
import com.shuqi.model.bean.OfferWallInfo;

/**
 * 热门应用Fragment
 * 
 * @author linyuren
 * 
 */
public class OfferWallHotAppFragment extends FragmentBase implements IEventListener,
        OnItemClickListener, OnClickListener {

    private OfferWallTopActivity mContext;
    private OfferWallModel model;
    private final static int INIT = EventTypeConstants.BASE;
    private final static int INITAPPDATASUCCESS = INIT + 1;
    private final int SHOW404 = INITAPPDATASUCCESS + 1;
    private final int LOADMORE_ERROR = SHOW404 + 1;

    private Animation imgAnimation;// 点击顶部应用图标动画
    /** 当前界面布局 */
    private View mCurretntLayout;
    private ListView mAppListView;
    private View mAppHeader;
    private MyListFooter mListFooter;
    /** 进度圈 */
    private LinearLayout mLoadingLayout;
    /** 网络错误 */
    private View mActNonetwork;
    /** 页数索引 */
    private int mHotAppPageIndex = 1;
    /** 热门应用列表总个数 */
    private int mAppPageTotal;

    private OfferWallGridAdapter appTopAdapter; // 应用顶部适配器
    private OfferWallListAdapter appListAdapter;// 应用列表适配器

    /** 存储热门应用顶部gridview数据 */
    private List<OfferWallInfo> appListTopData;
    /** 存储热门应用数据 */
    private List<OfferWallInfo> appListData = new ArrayList<OfferWallInfo>();

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case INIT:
                    fragmentLogicForward();
                    break;
                case INITAPPDATASUCCESS:
                    fragmentInitData();
                    break;
                case SHOW404:
                    mLoadingLayout.setVisibility(View.GONE);
                    mActNonetwork.setVisibility(View.VISIBLE);
                    break;
                case LOADMORE_ERROR:
                    mLoadingLayout.setVisibility(View.GONE);
                    mListFooter.loadingError();
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.model = new OfferWallModel(ShuqiApplication.getContext());
        this.model.addEventListener(this);
        if (container == null) {
            return null;
        }
        if (inflater == null) {
            inflater = LayoutInflater.from(mContext);
        }
        // 第一次实例化,bundle为传入参数
        if (savedInstanceState == null) {
            savedInstanceState = getArguments();
        }
        mCurretntLayout = inflater.inflate(R.layout.offer_wall_hotapp_layout, container, false);
        handler.sendEmptyMessage(INIT);
        return mCurretntLayout;
    }

    @Override
    public void onAttach(Activity activity) {
        if (mContext == null) {
            mContext = (OfferWallTopActivity) activity;
        }
        super.onAttach(activity);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retry:
                NetErrorProvider.getInstance().retry(this, new NetErrorListener() {
                    @Override
                    public void netErrorCallback() {
                        if (!Util.isNetworkConnected(mContext)) {
                            return;
                        }
                        mRequestAppList();
                    }
                });
                break;
        }
    }


    @Override
    public void fragmentLogicForward() {
        mAppListView = (ListView) mCurretntLayout.findViewById(R.id.lv_offerwall_app);
        mLoadingLayout = (LinearLayout) mCurretntLayout.findViewById(R.id.include_loading);
        mActNonetwork = (View) mCurretntLayout.findViewById(R.id.include_error);
        imgAnimation =
                AnimationUtils.loadAnimation(ShuqiApplication.getContext(), R.anim.imageview_alpha);
        mActNonetwork.findViewById(R.id.retry).setOnClickListener(this);

        appTopAdapter = new OfferWallGridAdapter(ShuqiApplication.getContext());

        MyFooterListener listener = new MyFooterListener() {

            @Override
            public void reload() {
                model.loadData(mHotAppPageIndex, "app");
                mListFooter.loadingStart();
            }

            @Override
            public void loadNext() {
                model.loadData(mHotAppPageIndex, "app");
                mListFooter.loadingStart();
            }

            @Override
            public boolean hasNext() {
                if (appListData == null || appListData.size() == 0) {
                    return false;
                }
                return (mAppPageTotal >= mHotAppPageIndex);
            }

        };
        mListFooter = new MyListFooter(ShuqiApplication.getContext(), listener);
        mAppListView.addFooterView(mListFooter);
        mAppListView.setOnItemClickListener(this);
        mRequestAppList();
        mListFooter.loadingStart();
    }

    private void mRequestAppList() {
        model.loadData(mHotAppPageIndex, "app");// 获取app数据
        mLoadingLayout.setVisibility(View.VISIBLE);
        mActNonetwork.setVisibility(View.GONE);
        mListFooter.loadingStart();
    }

    @Override
    public void onEvent(int event, Object data) {
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                mHotAppPageIndex++;
                List<OfferWallInfo> list = (List<OfferWallInfo>) data;
                if (list != null && list.size() > 0) {
                    mAppPageTotal = Integer.parseInt(list.get(0).getPageCount());
                    appListData.addAll(list);
                }
                handler.sendEmptyMessage(INITAPPDATASUCCESS);
                break;
            default:
                if (appListData == null || appListData.size() == 0) {
                    handler.sendEmptyMessage(SHOW404);
                } else {
                    handler.sendEmptyMessage(LOADMORE_ERROR);
                }
                break;
        }
    }

    @Override
    public void fragmentInitData() {
        if (mAppHeader == null) {
            mAppHeader =
                    LayoutInflater.from(ShuqiApplication.getContext()).inflate(
                            R.layout.header_offerwall, null);
        }
        if (mAppListView.getHeaderViewsCount() == 0) {
            mAppListView.addHeaderView(mAppHeader, null, false);
        }

        if (appListData == null || appListData.size() == 0) {
            ((LinearLayout) mAppHeader).getChildAt(0).setVisibility(View.GONE);
        } else {
            if (appListAdapter == null) {
                appListAdapter = new OfferWallListAdapter(mContext);
                OfferWallInfo info = appListData.get(0);
                ((LinearLayout) mAppHeader).getChildAt(0).setVisibility(View.VISIBLE);
                // 加载顶部栏数据
                GridView gv = (GridView) mAppHeader.findViewById(R.id.gv_offerwall);
                gv.setNumColumns(Integer.parseInt(info.getLineSize()));//

                appListTopData = new ArrayList<OfferWallInfo>();
                for (int i = 0; i < Integer.parseInt(info.getTopSize()); i++) { // 处理顶部数据
                    appListTopData.add(appListData.remove(0));
                }
                appTopAdapter.setList(appListTopData);
                gv.setAdapter(appTopAdapter);
                gv.setOnItemClickListener(this);

                int row =
                        (int) Math.ceil(Integer.parseInt(info.getTopSize()) * 1.0
                                / Integer.parseInt(info.getLineSize()));
                LayoutParams params = gv.getLayoutParams();
                // 每行高度 *行数
                params.height = Util.dip2px(ShuqiApplication.getContext(), 87.0f) * row;
                gv.setLayoutParams(params);
                if (appListTopData == null || appListTopData.size() == 0) {
                    ((View) mAppHeader.findViewById(R.id.offerwall_grid_hline))
                            .setVisibility(View.GONE);
                }
                appListAdapter.setList(appListData, "app");
                mAppListView.setAdapter(appListAdapter);
            } else {
                appListAdapter.notifyDataSetChanged();
            }
        }
        mListFooter.loadingSuccess();
        this.mLoadingLayout.setVisibility(View.GONE);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (appListData == null || appListData.size() == 0) {
            return;
        }
        OfferWallInfo info = null;
        Intent intent = new Intent(mContext, OfferWallItemActivity.class);
        intent.putExtra("from", "app");
        switch (parent.getId()) {
            case R.id.gv_offerwall:
                info = appListTopData.get(position);
                ImageView img = (ImageView) view.findViewById(R.id.itemlayout_offerwall_grid_iv);
                img.startAnimation(imgAnimation);
                intent.putExtra("itemid", info.getItemId());
                intent.putExtra("packagename", info.getPackageName());
                intent.putExtra("channel", info.getChannel());
                break;
            case R.id.lv_offerwall_app:
                info = appListData.get(position - 1);
                intent.putExtra("itemid", info.getItemId());
                intent.putExtra("packagename", info.getPackageName());
                intent.putExtra("channel", info.getChannel());
                break;
        }
        ActivityManager.getInstance().startActivity(intent, mContext);
    }
}
